package com.briup;


import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class TestDomj {
    public static void main(String[] args) {
        System.out.println("Hello Domj");
        TestDomj testDomj = new TestDomj();
        String filePath="src\\main\\java\\com\\briup\\class.xml";
        File file = new File(filePath);
        try {
            //dom4j文档对象
//            Document document = testDomj.parse(file);
//            System.out.println("document"+document);
            //调用自定义方法 处理xml文档
//            testDomj.handly(document);
//            创建xml文件
            Document document = testDomj.createDocument();
            testDomj.createXml(document);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public Document parse(File file) throws DocumentException{
        SAXReader reader = new SAXReader();
        Document document =reader.read(file);
        return document;
    }
    public void handly(Document document){
//        System.out.println("handly");
//        List<Node> list = document.selectNodes("//age");
//        list.forEach(node -> System.out.println(node.getName()+":"+node.getText()));

//        List<Node> list = document.selectNodes("/student/stu/*");
//        list.forEach(node -> System.out.println(node.getName()+":"+node.getText()));

        Element root = document.getRootElement();
        for(Iterator<Element> it = root.elementIterator(); it.hasNext();){
            Element element = it.next();
            System.out.println(element.getName()+":"+element.getText());
        }
        //获取根节点下指定名称的儿子节点
        for(Iterator<Element> it = root.elementIterator("stu"); it.hasNext();){
            Element element = it.next();
            System.out.println(element.getName()+":"+element.getText());
        }
        //获取根节点下属性
        for(Iterator<Attribute> it = root.attributeIterator(); it.hasNext();){
            Attribute element = it.next();
            System.out.println(element.getText());
            System.out.println(element.getValue());
        }

    }

    //创建xml文件
    //创建document对象
    public Document createDocument(){
        Document document = DocumentHelper.createDocument();
        Element root=document.addElement("root");
        Element stu=root.addElement("stu")
                .addAttribute("id","2024001")
                .addAttribute("gender","0");
        stu.addElement("name").addText("王五");
        stu.addElement("age").addText("23");
        return document;
    }
    //创建xml文件
    public void createXml(Document document){
        try{
            FileWriter fileWriter=new FileWriter("src\\main\\java\\com\\briup\\root.xml");
            document.write(fileWriter);
            fileWriter.close();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

}
